﻿using Fuse8.DomainFramework.Common;
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;

namespace Fuse8.ContentManagementFramework.SystemFacade.Utilities
{
    public static class ImageResizer
    {
        private static long ImageQuality { get { return CmsConfiguration.ResizerImageQuality; } }

        public static Size? GetImageDimension(string filePath)
        {
            Guard.ArgumentNotEmpty(filePath, "filePath");

            Size? result = null;

            //TO DO: check is image first
            try
            {
                using (var sourceImage = Image.FromFile(filePath))
                {
                    result = sourceImage.Size;
                }
            }
            catch
            { }

            return result;
        }

        public static string GetOrResize(string originalFileNameWithPath, int height, int width, string crop, out bool isExisting)
        {
            isExisting = true;
            var isCrop = crop != null && crop.ToLower() == "center";

            string fileName = Path.GetFileName(originalFileNameWithPath);

            string rootDirectory = Path.GetDirectoryName(originalFileNameWithPath);

            var resizedDirectory = height == Int32.MaxValue ?
               string.Format("w{0}", width) :
               width == int.MaxValue ? string.Format("h{0}", height) :
               string.Format("{0}x{1}", width, height);

            resizedDirectory = isCrop ? string.Format("crop_center_{0}", resizedDirectory) : resizedDirectory;

            resizedDirectory = Path.Combine(rootDirectory, resizedDirectory);

            fileName = Path.Combine(resizedDirectory, fileName);

            if (!File.Exists(fileName))
            {
                if (!Directory.Exists(resizedDirectory))
                {
                    Directory.CreateDirectory(resizedDirectory);
                }

                if (File.Exists(originalFileNameWithPath))
                {
                    using (var sourceImage = Image.FromFile(originalFileNameWithPath))
                    {
                        if (NeedToResize(sourceImage, height, width))
                        {
                            using (Bitmap resizedBitmap = GetResizedAndCropBitmap(sourceImage, height, width, crop))
                            {
                                resizedBitmap.SetResolution(sourceImage.HorizontalResolution, resizedBitmap.VerticalResolution);

                                var codec = GetImageCodecInfo(sourceImage.RawFormat);

                                using (var encoderParams = GetEncoderParameters())
                                {
                                    using (var file = File.Create(fileName))
                                    {
                                        resizedBitmap.Save(file, codec, encoderParams);
                                    }
                                }
                            }
                        }
                        else
                        {
                            fileName = originalFileNameWithPath;
                        }
                    }
                }
                else
                {
                    isExisting = false;
                }
            }

            return fileName;
        }

        private static bool NeedToResize(Image sourceImage, int newHeight, int newWidth)
        {
            Guard.ArgumentNotNull(sourceImage, "sourceImage");

            double dAspectRatio = (double)sourceImage.Width / (double)sourceImage.Height;

            // calculate new height/width
            if (newHeight == Int32.MaxValue)
            {
                newHeight = (int)(newWidth / dAspectRatio);
            }
            else if (newWidth == Int32.MaxValue)
            {
                newWidth = (int)(newHeight * dAspectRatio);
            }
            else
            {
                // if both new height and width are specified
                // the first of the values that is reached will be the limiting value
                int nNewTempHeight = (int)(newWidth / dAspectRatio);

                if (nNewTempHeight < newHeight)
                {
                    newHeight = nNewTempHeight;
                }
                else
                {
                    newWidth = (int)(newHeight * dAspectRatio);
                }
            }

            return (sourceImage.Height > newHeight) && (sourceImage.Width > newWidth);
        }

        private static ImageCodecInfo GetImageCodecInfo(ImageFormat imageFormat)
        {
            Guard.ArgumentNotNull(imageFormat, "imageFormat");

            var imageFormatId = imageFormat.Guid;
            var codecInfos = ImageCodecInfo.GetImageEncoders();

            // Convert gif to png to properly process transparent images.
            if (imageFormatId == ImageFormat.Gif.Guid)
            {
                imageFormatId = ImageFormat.Png.Guid;
            }

            // If codec is not found, use jpeg codec by default.
            var codec = codecInfos.FirstOrDefault(c => c.FormatID == imageFormatId) ??
                codecInfos.First(c => c.FormatID == ImageFormat.Jpeg.Guid);

            return codec;
        }

        private static EncoderParameters GetEncoderParameters()
        {
            var encps = new EncoderParameters(1);

            encps.Param[0] = new EncoderParameter(Encoder.Quality, ImageQuality);

            return encps;
        }

        private static Bitmap GetResizedAndCropBitmap(Image sourceImage, int height, int width, string crop)
        {
            Guard.ArgumentNotNull(sourceImage, "sourceImage");

            var newHeight = height = height > sourceImage.Height ? sourceImage.Height : height;
            var newWidth = width = width > sourceImage.Width ? sourceImage.Width : width;

            var isCrop = crop != null && crop.ToLower() == "center";
            double dAspectRatio = (double)sourceImage.Width / (double)sourceImage.Height;

            // calculate new height/width
            var calculateNewHeight = (int)Math.Round(newWidth / dAspectRatio);
            var calculateNewWidth = (int)Math.Round(newHeight * dAspectRatio);

            if (height == Int32.MaxValue)
            {
                height = calculateNewHeight;
            }
            else if (width == Int32.MaxValue)
            {
                width = calculateNewWidth;
            }
            else
            {
                if (isCrop)
                {
                    if (dAspectRatio != 1)
                    {
                        if (dAspectRatio < 1)
                        {
                            if (width != height)
                            {
                                var tempHeight = (int)(width / dAspectRatio);
                                if (tempHeight < height)
                                {
                                    width = calculateNewWidth;
                                }
                                else
                                {
                                    height = tempHeight;
                                }
                            }
                            else
                            {
                                height = calculateNewHeight;
                            }
                        }
                        else
                        {
                            if (width != height)
                            {
                                var tempWidth = (int)(height * dAspectRatio);
                                if (tempWidth < width)
                                {
                                    height = calculateNewHeight;
                                }
                                else
                                {
                                    width = tempWidth;
                                }
                            }
                            else
                            {
                                width = calculateNewWidth;
                            }
                        }
                    }
                    else if (dAspectRatio == 1)
                    {
                        if (newWidth > newHeight)
                        {
                            width = height = newWidth;
                        }
                        else if (newHeight > newWidth)
                        {
                            width = height = newHeight;
                        }
                    }
                }
                else
                {
                    var nNewTempHeight = (int)Math.Round(width / dAspectRatio);

                    if (nNewTempHeight < height)
                    {
                        height = nNewTempHeight;
                    }
                    else
                    {
                        width = (int)Math.Round(newHeight * dAspectRatio);
                    }
                }
            }

            // do clever stuff with resizing and encoding
            var bitmap = new Bitmap(width, height);

            using (var gfx = Graphics.FromImage(bitmap))
            {
                gfx.InterpolationMode = InterpolationMode.HighQualityBicubic;
                gfx.PixelOffsetMode = PixelOffsetMode.HighQuality;
                gfx.DrawImage(sourceImage, 0, 0, width, height);
            }

            return isCrop ? CropImage(bitmap, newWidth, newHeight) : bitmap;
        }

        private static Bitmap CropImage(Bitmap img, int width, int height)
        {
            var cropArea = new Rectangle
            {
                Width = width > img.Width ? img.Width : width,
                Height = height > img.Height ? img.Height : height,
                X = img.Width > width ? (img.Width / 2) - (width / 2) : 0,
                Y = img.Height > height ? (img.Height / 2) - (height / 2) : 0
            };
            return img.Clone(cropArea, img.PixelFormat);
        }
    }
}